const express=require("express")
const information=express.Router();
const fs=require("fs")
const  {recommendTable:singlebase}=require("../database/singlebase");



information.get("/:num", async (req, res, next) => {
    let data = await singlebase.find().skip(Number(req.params.num)).limit(10);
    res.send(data)
})

//根据ID 查询信息
information.get("/search/:id",(req,res,next)=>{
    singlebase.find({useID:req.params.id},(err,data)=>{
        // console.log(data);
        res.send(data)
    })
})

information.get("/",  (req,res,next)=>{
    singlebase.count((err,count)=>{
     
        res.send(count.toString())
    })
 })
 
//下载请求
information.post('/download',async (req,res,next)=>{
    if (!req.body.id && !req.body.time) {
        res.send({
            code:5000,
            msg:'查询字段缺失'
        })
    }
    let imgpath=false
    let data=await singlebase.find({
        useID:req.body.id,
        dataTime:req.body.time
    })
    if (data.length) {
        // data[0].imgUrl.forEach((v,i)=>{
        //     if (v.dataTime===req.body.time) {
        //         imgpath=v.imgUrl
        //     }
        // })
        imgpath=data[0].imgUrl
        if (imgpath) {
            imgpath = imgpath.replace('http://localhost:5055/','./pub/')
            let imgbuff=fs.readFileSync(imgpath)
            res.send({ imgSrc : imgbuff.toString("base64"),imgInfo: data})
        } else {
            res.send({
                code:5000,
                msg:'不存在图片记录'
            }) 
            
        }
        
    } else {
        res.send({
            code:5000,
            msg:'不存在图片记录'
        })
    }
})


//返回相关信息 grade:年级 college：学号 classes:班级
information.get("/college/:list",(req,res,next)=>{
    let searchList=req.params.list
   singlebase.distinct(searchList,(err,data)=>{
       res.send(data)
   })
})

// 根据条件查询
information.post("/search",(req,res,next)=>{
    let query={};
    // let useID=req.body.useID
    // let grade=req.body.grade
    // let college=req.body.college
    // let classes=req.body.classes
    if (req.body.secretID) delete req.body.secretID
    for (let key in req.body) {
        if (req.body[key]!="") {
            query[key]=req.body[key]
        }
    }
    singlebase.find(query,(err,data)=>{
        console.log(data);
        res.send(data)
    })
})

information.post("/del", async(req,res,next)=>{

    let data=await singlebase.remove({
        useID:req.body.id,
        dataTime:req.body.time
    })
    
    if (data.deletedCount) {
        res.send({
            code:0,
            msg:'删除成功'
        })
    }else{
        res.send({
            code:5000,
            msg:'该数据不存在'
        })
    }
})

module.exports=information